<template>
  <div style="margin-top: 10px;">
    <!--  搜索条件  -->
    <div>
      <el-select v-model="searchForm.belongEnd" style="margin-right: 10px; width: 130px;"
                 @change="onSelectedBelongEnd($event)"
                 filterable clearable placeholder="-请选择归属端-">
        <el-option
            v-for="item in belongEndList"
            :key="item.id"
            :label="item.name"
            :value="item.id">
        </el-option>
      </el-select>

      <el-select v-model="searchForm.userId" style="margin-right: 10px; width: 130px;"
                 @change="onSelectedUser($event)"
                 filterable clearable placeholder="-请选择负责人-">
        <el-option
            v-for="item in userList"
            :key="item.id"
            :label="item.name"
            :value="item.id">
        </el-option>
      </el-select>

      <!-- 输入框，可按此方式根据实际情况动态修改或扩增 -->
      <el-input placeholder="请输入应用名称/描述/端口号搜索" prefix-icon="el-icon-search"
                clearable
                @clear="initDataList"
                style="width: 250px;margin-right: 10px" v-model="searchForm.appName"
                @keydown.enter.native="initDataList">
      </el-input>

      <el-button type="primary" icon="el-icon-search" @click="search">
        查询
      </el-button>

      <el-select v-model="searchForm.env" style="margin-left: 10px; float: right; width: 100px;"
                 @change="onSelectedEnv($event)"
                 filterable>
        <el-option
            v-for="item in envList"
            :key="item.id"
            :label="item.name"
            :value="item.id">
        </el-option>
      </el-select>
      <el-button type="primary" icon="el-icon-plus" @click="add" style="float: right">
        新增
      </el-button>
      <el-button icon="el-icon-refresh" style="display: inline-flex;margin-right: 8px;float: right" type="primary"
                 @click="flushTable"></el-button>
    </div>

    <div style="margin-top: 10px; height: auto;">
      <el-table :data="dataList" border stripe size="mini" height="500" style="width: 100%" :header-cell-style="{background:'#f5f7fa',color:'#606266'}">
        <el-table-column type="index" label="序号" fixed align="center" width="50px;"></el-table-column>
        <!-- <el-table-column type="selection" align="left" width="55"></el-table-column> -->
        <el-table-column prop="id" label="主键ID" align="left" v-if="idShow"></el-table-column>

        <el-table-column prop="appName" label="应用名称" fixed width="150px;" align="left" :show-overflow-tooltip="true">
          <el-tag slot-scope="scope" @click="handleCopy(scope.row.appName)">{{ scope.row.appName }}</el-tag>
        </el-table-column>

        <el-table-column prop="appDesc" label="应用描述" width="200px;" align="left" :show-overflow-tooltip="true">
          <el-tag slot-scope="scope" @click="handleCopy(scope.row.appDesc)">{{ scope.row.appDesc }}</el-tag>
        </el-table-column>

        <el-table-column prop="port" label="应用端口号" width="100px;" align="center" :show-overflow-tooltip="true">
          <el-tag slot-scope="scope" @click="handleCopy(scope.row.port)">{{ scope.row.port }}</el-tag>
        </el-table-column>

        <el-table-column prop="swaggerUrl" label="API文档地址" width="250px;" :show-overflow-tooltip="true">
          <!--超链接-->
          <template slot-scope="scope">
            <a :href="scope.row.swaggerUrl" target="_blank">
              <el-tag>{{ scope.row.swaggerUrl }}</el-tag>
            </a>
          </template>
        </el-table-column>

        <el-table-column prop="belongEnd" label="归属端代号" width="20px;" :show-overflow-tooltip="true" v-if="false">
          <el-tag slot-scope="scope" @click="handleCopy(scope.row.belongEnd)">{{ scope.row.belongEnd }}</el-tag>
        </el-table-column>
        <el-table-column prop="belongEndName" label="归属端" width="100px;" :show-overflow-tooltip="true">
          <el-tag slot-scope="scope" @click="handleCopy(scope.row.belongEndName)">{{ scope.row.belongEndName }}</el-tag>
        </el-table-column>

        <el-table-column prop="userId" label="负责人ID" width="20px;" :show-overflow-tooltip="true" v-if="false">
          <el-tag slot-scope="scope" @click="handleCopy(scope.row.userId)">{{ scope.row.userId }}</el-tag>
        </el-table-column>
        <el-table-column prop="userName" label="负责人" width="100px;" :show-overflow-tooltip="true">
          <el-tag slot-scope="scope" @click="handleCopy(scope.row.userName)">{{ scope.row.userName }}</el-tag>
        </el-table-column>

        <!-- 创建时间、更新时间必备 -->
        <el-table-column prop="createTime" label="创建时间" width="150px;" align="center" :show-overflow-tooltip="true"></el-table-column>
        <el-table-column prop="updateTime" label="更新时间" width="150px;" align="center" :show-overflow-tooltip="true"></el-table-column>

        <!-- 操作必备 -->
        <el-table-column label="操作" align="center" fixed="right" width="300px;">
          <template slot-scope="scope">
            <el-button @click="interfaceTest(scope.row)" class="el-icon-aim" type="success" v-if="false">接口测试</el-button>
            <el-button @click="view(scope.row)" class="el-icon-view" type="primary">查看</el-button>
            <el-button @click="edit(scope.row)" class="el-icon-edit" type="primary">编辑</el-button>
            <el-button @click="del(scope.row)" class="el-icon-delete" type="danger">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <div style="display: flex;justify-content: flex-end">
      <el-pagination
          background
          :current-page.sync="searchForm.pageNum"
          @size-change="pageSizeChange"
          @current-change="pageNumChange"
          layout="sizes, prev, pager, next, jumper, ->, total, slot"
          :total="total">
      </el-pagination>
    </div>

    <!-- 查看/新增/编辑 对话框 -->
    <div>
      <el-dialog v-dialogDrag
                 :modal-append-to-body="false"
                 :title="operateTitle"
                 :visible.sync="saveDialogVisible"
                 width="20%"
                 top="20vh">

        <el-form :model="saveForm" :rules="saveFormRules" ref="saveFormRef" label-width="100px" label-position="left">
          <el-form-item label="主键ID" prop="id" v-show="false">
            <el-input v-model="saveForm.id"></el-input>
          </el-form-item>

          <el-form-item label="归属端" prop="belongEnd">
            <el-select class="item" v-model="saveForm.belongEnd"
                       @change="onFormSelectedBelongEnd($event)" :disabled="viewMode"
                       filterable placeholder="-请选择归属端-">
              <el-option
                  v-for="item in belongEndList"
                  :key="item.id"
                  :label="item.name"
                  :value="item.id">
              </el-option>
            </el-select>
          </el-form-item>

          <el-form-item label="应用名称" prop="appName">
            <el-input v-model="saveForm.appName" maxlength="64" :disabled="viewMode" placeholder="请输入应用名称"></el-input>
          </el-form-item>

          <el-form-item label="应用端口" prop="port">
            <el-input v-model="saveForm.port" maxlength="32" :disabled="viewMode" placeholder="请输入应用端口"></el-input>
          </el-form-item>

          <el-form-item label="负责人" prop="userId">
            <el-select class="item" v-model="saveForm.userId"
                       @change="onFormSelectedUser($event)" :disabled="viewMode"
                       filterable placeholder="-请选择负责人-">
              <el-option
                  v-for="item in userList"
                  :key="item.id"
                  :label="item.name"
                  :value="item.id">
              </el-option>
            </el-select>
          </el-form-item>

          <el-form-item label="环境" prop="env">
            <el-select class="item" v-model="saveForm.env"
                       @change="onFormSelectedEnv($event)" disabled="disabled"
                       filterable placeholder="-请选择环境-">
              <el-option
                  v-for="item in envList"
                  :key="item.id"
                  :label="item.name"
                  :value="item.id">
              </el-option>
            </el-select>
          </el-form-item>

          <el-form-item label="API文档地址" prop="swaggerUrl">
            <el-input type="textarea" autosize v-model="saveForm.swaggerUrl" maxlength="255" style="width: 215px;" placeholder="请输入API文档地址，不填则为默认地址" :disabled="viewMode"></el-input>
          </el-form-item>

          <el-form-item label="应用描述" prop="appDesc">
            <el-input type="textarea" autosize v-model="saveForm.appDesc" maxlength="128" show-word-limit style="width: 215px;" :disabled="viewMode" placeholder="请输入应用描述"></el-input>
          </el-form-item>
        </el-form>

        <span slot="footer" class="dialog-footer">
          <el-button type="primary" @click="formReset" v-if="resetVisible">重置</el-button>
          <el-button type="primary" @click="saveCancel">取消</el-button>
          <el-button type="primary" @click="save" v-if="!viewMode">确定</el-button>
        </span>
      </el-dialog>
    </div>
  </div>
</template>

<script>
import {Message} from "element-ui";
import {deepClone, unique} from "@/utils/tool";
import '@/utils/dialog'

export default {
  name: "AppManage",
  data() {
    return {

      belongEndList: [{id: 1, name: '企业端'}, {id: 2, name: '医端'}, {id: 3, name: '患端'}, {id: 4, name: '商业端' }, {id: 5, name: '中台'}],
      userList: [],
      envList: [{id: 'dev', name: '开发环境'}, {id: 'test', name: '测试环境'}, {id: 'local', name: '本地环境'}],
      // 列表数据
      dataList: [],
      // 列表数据总量
      total: 0,
      // 列表数据的ID是否显示(默认不显示)
      idShow: false,

      // 【getPageInfo】接口需要的字段封装对象
      searchForm: {
        appName: '',

        belongEnd: '',

        userId: '',

        env: 'dev',

        // 分页查询条件
        pageNum: 1,
        pageSize: 10,
        // 可根据【getPageInfo】接口动态增加字段
      },

      // 查看、新增、编辑对话框标题
      operateTitle: '标题',
      // 查看、新增、编辑对话框是否可见
      saveDialogVisible: false,
      // 查看、新增、编辑对话框的重置按钮是否可见
      resetVisible: false,
      // 是否是查看模式
      viewMode: false,

      // 【save】接口需要的字段封装对象
      saveForm: {
        id: '',
        appName: '',
        appDesc: '',
        port: '',
        belongEnd: '',
        belongEndName: '',
        userId: '',
        userName: '',
        swaggerUrl: '',
        env: '',
      },
      tempEnv: 'dev',
      // 【save】接口参数用户输入校验
      saveFormRules: {
        appName: [
          // { validator: validateAppName, trigger: 'blur' },
          {required: true, message: '请输入应用英文名称', trigger: 'blur'},
          {min: 1, max: 64, message: '长度在 1 到 64 个字符', trigger: 'blur'},
          {pattern: /^[a-z\\-]+$/, message: '应用名称只能由小写英文和中划线组成！'}
        ],
        appDesc: [
          {required: false, message: '请输入应用描述', trigger: 'blur'},
          {min: 1, max: 128, message: '长度在 1 到 128 个字符', trigger: 'blur'}
        ],
        port: [
          {required: true, message: '请输入应用端口', trigger: 'blur'},
          {min: 1, max: 16, message: '长度在 1 到 16 个字符', trigger: 'blur'},
          {pattern: /[1-9]\d*/, message: '请输入正确的端口号'},
        ],
        belongEnd: [
          {required: true, message: '请选择归属端', trigger: 'blur'},
        ],
        userId: [
          {required: true, message: '请选择负责人', trigger: 'blur'},
        ],
        env: [
          {required: true, message: '请选择环境', trigger: 'blur'},
        ],
        swaggerUrl: [
          {pattern: /^((https|http|ftp|rtsp|mms)?:\/\/)[^\s]+/, message: '请输入正确的API地址！'}
        ],
      },
    }
  },

  // 初始化组件时加载数据
  mounted() {
    // 加载表格数据
    this.initDataList();
    // 加载下拉选框数据
    this.initUserList();
  },

  methods: {
    // 调用后端【getPageInfo】接口获取表格数据
    initDataList() {
      this.getRequest("/appManage/getPageInfo", this.searchForm).then(resp => {
        this.loading = true;
        if (resp && resp.status === 200) {
          // resp.data.forEach(function(obj) {
          //   departmentList.push({'value': obj.id, 'label': obj.name});
          // });
          this.dataList = resp.data.list;
          this.total = resp.data.total;
          this.loading = false;
        }
      })
    },

    // 调用后端【getList】接口获取集合数据给下拉选框赋值
    initUserList() {
      this.getRequest("/sysUser/getList").then(resp => {
        this.loading = true;
        if (resp && resp.status === 200) {
          // resp.data.forEach(function(obj) {
          //   departmentList.push({'value': obj.id, 'label': obj.name});
          // });
          this.userList = resp.data;
          // 去重处理(按需设定，可将需要去重的值设置给id属性)
          const tempList = deepClone(this.userList);
          let list = tempList.map((item,index) => {
            return {
              index: index,
              id: item.id,
              name: item.name,
            };
          });
          // 根据id去重
          this.userList = unique(list);
        }
      })
    },

    // 点击搜索搜索
    search() {
      this.initDataList();
    },

    flushTable() {
      this.initDataList();
      Message.success("刷新成功");
    },

    // 页码切换
    pageNumChange(page) {
      this.searchForm.pageNum = page;
      this.initDataList();
    },
    // 每页数量切换
    pageSizeChange(size) {
      this.searchForm.pageSize = size;
      this.searchForm.pageNum = 1;
      this.initDataList();
    },

    // 点击新增
    add() {
      this.saveForm = {env: this.tempEnv};
      if (this.$refs['saveFormRef'] !== undefined) {
        this.$refs['saveFormRef'].resetFields();
      }
      this.operateTitle = '新增数据';
      this.viewMode = false;
      this.resetVisible = true;
      this.saveDialogVisible = true;
    },
    // 点击查看
    view(row) {
      this.operateTitle = "查看数据";
      this.saveForm = deepClone(row);
      this.saveForm.env = this.tempEnv;
      this.viewMode = true;
      this.resetVisible = false;
      this.saveDialogVisible = true;
    },
    // 点击编辑
    edit(row) {
      this.operateTitle = '编辑数据';
      this.saveForm = deepClone(row);
      this.saveForm.env = this.tempEnv;
      this.viewMode = false;
      this.resetVisible = false;
      this.saveDialogVisible = true;
    },
    // 点击删除
    del(row) {
      this.$confirm('删除后无法恢复！！！确认删除?')
          .then(() => {
            this.putRequest('/appManage/delete', row).then(resp => {
              if (resp && resp.status === 200) {
                this.initDataList();
                Message.success("删除成功");
              }
            })
          }).catch(ex => {
        console.error("删除异常：" + ex)
      });
    },

    interfaceTest(row) {
      Message.success("开始接口测试：" + JSON.stringify(row));
    },

    // 新增、编辑对话框表单重置
    formReset() {
      if (this.$refs['saveFormRef'] !== undefined) {
        this.$refs['saveFormRef'].resetFields();
      }
      Message.success("重置成功")
    },
    // 新增、编辑对话框表单取消
    saveCancel() {
      this.saveDialogVisible = false;
    },
    // 新增、编辑对话框表单确定
    save() {
      const id = this.saveForm.id;
      this.$refs['saveFormRef'].validate((valid) => {
        if (valid && !id) {
          // 如果id不存在，则新增数据
          this.postRequest('/appManage/insert', this.saveForm).then((resp => {
            if (resp && resp.status === 200) {
              this.initDataList();
              this.saveDialogVisible = false;
              Message.success("新增成功");
            }
          }));
        } else if (id) {
          // 如果id存在，则更新数据
          this.postRequest('/appManage/update', this.saveForm).then((resp => {
            if (resp && resp.status === 200) {
              this.initDataList();
              this.saveDialogVisible = false;
              Message.success("更新成功");
            }
          }));
        } else {
          return false;
        }
      })
    },

    onSelectedBelongEnd(eventId) {
      if (!eventId) {
        this.searchForm.belongEnd = '';
        this.searchForm.belongEndName = '';
        this.initDataList();
        return;
      }
      let obj = this.belongEndList.find(item => {
        return item.id === eventId;
      });
      this.searchForm.belongEnd = eventId;
      this.searchForm.belongEndName = obj.name;
      this.initDataList();
    },

    onSelectedEnv(envId) {
      if (!envId) {
        this.searchForm.env = '';
        this.tempEnv = '';
        this.initDataList();
        return;
      }
      this.searchForm.env = envId;
      this.tempEnv = envId;
      this.initDataList();
    },

    onFormSelectedEnv(eventId) {
      if (!eventId) {
        this.saveForm.env = '';
        return false;
      }
      let obj = this.envList.find(item => {
        return item.id === eventId;
      });
      this.saveForm.env = eventId;
    },

    onSelectedUser(eventId) {
      if (!eventId) {
        this.searchForm.userId = '';
        this.searchForm.userName = '';
        this.initDataList();
        return;
      }
      let obj = this.userList.find(item => {
        return item.id === eventId;
      });
      this.searchForm.userId = eventId;
      this.searchForm.userName = obj.name;
      this.initDataList();
    },

    onFormSelectedBelongEnd(eventId) {
      if (!eventId) {
        this.saveForm.belongEnd = '';
        this.saveForm.belongEndName = '';
        return false;
      }
      let obj = this.belongEndList.find(item => {
        return item.id === eventId;
      });
      this.saveForm.belongEnd = eventId;
      this.saveForm.belongEndName = obj.name;
    },

    onFormSelectedUser(eventId) {
      if (!eventId) {
        this.saveForm.userId = '';
        this.saveForm.userName = '';
        return false;
      }
      let obj = this.userList.find(item => {
        return item.id === eventId;
      });
      this.saveForm.userId = eventId;
      this.saveForm.userName = obj.name;
    },

    // 复制单元格 公共方法
    handleCopy(obj) {
      this.$copyText(obj).then(
          function () {
            Message.success("复制成功！");
          },
          function () {
            Message.error("复制失败，请手动复制！");
          }
      );
    },
  },
}
</script>

<style scoped>
  .el-input {
    width: 215px;
  }
</style>